#!/bin/bash

# 检查是否提供了bag文件名参数
if [ -z "$1" ]; then
    echo "No bag filename specified."
    exit 1
fi

BAG_NAME=$1
LOG_DIR=~/.ros/log/tmux_logs/

# 创建日志目录（如果不存在）
mkdir -p "$LOG_DIR"

SESSION_NAME1="winch_main_process"
SESSION_NAME2="winch_socket_process"

# 确定日志文件路径
LOG_FILE1="${BAG_NAME}_${SESSION_NAME1}.txt"
LOG_FILE2="${BAG_NAME}_${SESSION_NAME2}.txt"

# 检查并开始记录tmux日志的函数
start_logging() {
    local session_name=$1
    local log_file=$2
    local pane_id=$3

    while true; do
        if tmux has-session -t "$session_name" 2>/dev/null; then
            tmux pipe-pane -t "${session_name}:${pane_id}" -o "cat >> $log_file"
            echo "Started logging tmux pane output for session $session_name to $log_file"
            break
        else
            echo "Session $session_name not found. Retrying in 1 second..."
            sleep 1
        fi
    done
}

# 启动后台任务并记录父进程 PID
start_logging "$SESSION_NAME1" "$LOG_FILE1" "0.0" & echo $! > /tmp/start_logging_1.pid
start_logging "$SESSION_NAME2" "$LOG_FILE2" "0.0" & echo $! > /tmp/start_logging_2.pid

ros2 bag record -o "$BAG_NAME" -a &
